package controller;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Paper;

import core.PgSQL;
import core.Tool;
import core.View;

public class PaperList extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static PgSQL db = PgSQL.getInstance();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int limit = 12;
		int page = Math.max(1, Tool.intval(request.getParameter("page")));
		int offset = (page - 1) * limit;
		
		PreparedStatement ps = db.prepareStatement("SELECT p.*,u.username FROM qz_paper p LEFT JOIN qz_user u ON u.uid=p.authorid WHERE true ORDER BY pid OFFSET ? LIMIT ?");
		try{
			ps.setInt(1, offset);
			ps.setInt(2, limit);
			ResultSet rs = ps.executeQuery();
			
			LinkedList<Paper> plist = new LinkedList<Paper>();
			LinkedList<String> ulist = new LinkedList<String>();
			while(rs.next()){
				Paper p = Paper.fromDatabase(rs);
				plist.add(p);
				ulist.add(rs.getString(7));
			}
			request.setAttribute("plist[]", plist.toArray(new Paper[0]));
			request.setAttribute("ulist[]", ulist.toArray(new String[0]));

			rs = db.query("SELECT COUNT(*) FROM qz_paper");
			rs.next();
			int total = rs.getInt(1);
			String mpage = View.mpage(total, page, limit, "PaperList");
			request.setAttribute("mpage", mpage);
			
			View.show(request, response, "paper_list");
			
		}catch(SQLException e){
			e.printStackTrace();
			View.showMessage(request, response,  "Sorry, there's something wrong with our server. We are trying to solve it.", "back");
		}
	}
}
